<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 消息提示 -->
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="parseInt(activeindex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧标签页 -->
      <el-form
        :model="addRuleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeindex"
          :tab-position="'left'"
          :before-leave="beforeLeaveTag"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addRuleForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addRuleForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addRuleForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addRuleForm.goods_cat"
                :options="CategoriesList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 动态参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(cb, index) in item.attr_vals"
                  :key="index"
                  :label="cb"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              :action="action"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本框 -->
            <quill-editor v-model="addRuleForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img :src="imgPicUrl" alt="" class="uploadPic" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 步骤进度
      activeindex: "0",
      //   表单数据
      addRuleForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 上传的图片地址
        pics: [],
        // 富文本框内容
        goods_introduce: "",
        attrs: [],
      },
      // 表单校验规则
      rules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
      },
      //   级联选择器的分类表单数据(得到的结果)
      CategoriesList: [],
      // 级联选择器的配置
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      //   many参数列表
      manyList: [],
      // only属性列表
      onlyList: [],
      // 图片上传路径
      action: "http://127.0.0.1:8888/api/private/v1/upload",
      // 上传图片请求头信息
      headersObj: {
        Authorization: sessionStorage.getItem("TOKEN"),
      },
      // 对话框是否展示
      picDialogVisible: false,
      // 图片本地地址
      imgPicUrl: "",
    };
  },
  computed: {
    cateId() {
      return this.addRuleForm.goods_cat[this.addRuleForm.goods_cat.length - 1];
    },
  },
  methods: {
    // 获取级联选择器的分类表单数据
    async getCategoriesList() {
      const { data: res } = await this.$http.get(`categories`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取列表失败");
      }
      this.CategoriesList = res.data;
    },
    // 获取分类参数列表
    // sel参数只能是：  many或者only
    async getAttributesList(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数失败");
      }
      console.log(res);

      if (sel === "many") {
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        this.manyList = res.data;
      }
      if (sel === "only") {
        this.onlyList = res.data;
      }
    },

    // 级联选择器值改变的时候触发这个函数
    handleChange() {
      console.log(this.addRuleForm.goods_cat);
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = [];
      } else {
        // TODO:
      }
    },
    // 每次跳转标签页的时候触发这个函数
    beforeLeaveTag(activeName, oldActiveName) {
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.$message.error("商品分类不能为空！！！");
        return false;
      } else {
        if (activeName === "1") {
          this.getAttributesList("many");
          // console.log(this.manyList)
        }

        if (activeName === "2") {
          this.getAttributesList("only");
        }
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
      this.imgPicUrl = file.response.data.url;
      this.picDialogVisible = true;
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      const removePicInfo = file.response.data.tmp_path;
      const i = this.addRuleForm.pics.findIndex((value, index, arr) => {
        return value.pic === removePicInfo;
      });
      this.addRuleForm.pics.splice(i, 1);
      // console.log(this.addRuleForm)
    },
    // 文件传送成功触发这个函数
    handleSuccess(response, file, fileList) {
      // console.log(response.data.tmp_path)
      const picInfo = { pic: response.data.tmp_path };
      this.addRuleForm.pics.push(picInfo);
    },
    // 点击添加商品按钮完成最后操作发送http请求
    add() {
      this.$refs.ruleFormRef.validate(async (valide) => {
        if (!valide) return this.$message.error("请填写完整的信息");
        const form = _.cloneDeep(this.addRuleForm);
        form.goods_cat = form.goods_cat.join(",");
        // 处理商品参数信息
        this.manyList.forEach((item) => {
          const attrObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          form.attrs.push(attrObj);
        });
        // 处理商品属性信息
        this.onlyList.forEach((item) => {
          const attrObj = { attr_id: item.attr_id, attr_value: item.attr_vals };
          form.attrs.push(attrObj)
        });

        // 发送ajax请求
        const {data:res} = await this.$http.post('goods',form)
        if(res.meta.status!== 201) {
          return this.$message.error("添加商品失败")
        }
        this.$message.success("添加商品成功！")
        this.$router.push('/goods')
      });
    },
  },
  mounted() {
    this.getCategoriesList();
  },
};
</script>

<style scoped lang="less">
.el-steps {
  margin-top: 10px;
  margin-bottom: 10px;
}
.el-checkbox {
  margin: 0px 10px 0 0 !important;
}
.uploadPic {
  width: 100%;
  height: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>